package com.macrohard.admin.controller;

import com.macrohard.admin.config.properties.FileProperties;
import com.macrohard.common.base.response.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

@RestController
@RequestMapping("file")
@Api(tags = "文件接口")
public class FileController {
	@Resource
	private FileProperties fileProperties;

	@PostMapping("upload")
	@ApiOperation("上传图片")
	public R upload(@RequestPart("file") MultipartFile file) throws IOException {
		if (Objects.isNull(file)) {
			return R.wrapEffectResult(false);
		}
		String uploadPath = fileProperties.getPath();
		File path = new File(uploadPath).getCanonicalFile();
		if(!path.exists()){
			path.mkdirs();
		}
		String oriName = file.getOriginalFilename();
		String fileName = UUID.randomUUID().toString().substring(0, 18) + oriName.substring(oriName.lastIndexOf("."));
		File descFile = new File(path.getAbsolutePath() + "/" + fileName);
		file.transferTo(descFile);
		return R.ok("操作成功", fileName);
	}
}
